package com.bite.redisDemo;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Set;

@Slf4j
public class RedisDemoSet {

    public static void test1(Jedis jedis){
        System.out.println("sadd 和 smembers");
        jedis.flushAll();

        jedis.sadd("key1","111","222","333");
        Set<String> result = jedis.smembers("key1");
        System.out.println("result:"+result);
    }

    public static void test2(Jedis jedis){
        System.out.println("sismember");
        jedis.flushAll();

        jedis.sadd("key1","111","222","333");
        boolean result1 = jedis.sismember("key1", "111");
        boolean result2 = jedis.sismember("key1", "444");
        System.out.println("result1: " + result1 + " result2: " + result2);
    }

    public static void test3(Jedis jedis){
        System.out.println("scard: 获取元素个数");
        jedis.flushAll();

        jedis.sadd("key1","111","222","333");
        long resultScard = jedis.scard("key1");
        System.out.println("resultScard: " + resultScard);
    }

    public static void test4(Jedis jedis){
        System.out.println("spop: 随机删除");
        jedis.flushAll();

        jedis.sadd("key1","111","222","333");
        System.out.println(jedis.spop("key1"));
        System.out.println(jedis.spop("key1"));
        System.out.println(jedis.spop("key1"));
        System.out.println(jedis.spop("key1"));
    }

    public static void test5(Jedis jedis){
        System.out.println("sinter: 求交集");
        jedis.flushAll();
        jedis.sadd("key1","111","222","333");
        jedis.sadd("key2","111","333","444","555");
        Set<String> sinter = jedis.sinter("key1", "key2");
        System.out.println("sinter: " + sinter);

    }

    public static void test6(Jedis jedis){
        System.out.println("sinterstore: 求交集,并且把结果存储到一个新的key中");
        jedis.flushAll();

        jedis.sadd("key1","111","222","333");
        jedis.sadd("key2","111","333","444","555");
        jedis.sadd("key3","999");
        System.out.println("key3原来存储的数据: "+jedis.smembers("key3"));

        jedis.sinterstore("key3","key1","key2");
        Set<String> resultKey3 = jedis.smembers("key3");
        System.out.println("key1,key2求交集,结果存储在key3中,结果为: "+resultKey3);
        System.out.println("由上可知, key3 原来的 999 被去掉了");
    }


    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");
        try(Jedis jedis = jedisPool.getResource()) {
//            test1(jedis);
//            test2(jedis);
//            test3(jedis);
//            test4(jedis);
//            test5(jedis);
            test6(jedis);

        }catch (Exception e){
            log.error("内部错误: "+e.getMessage());
        }
    }
}
